import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Link, History } from 'react-router';

import {
  Well,
  Row,
  Col
} from 'react-bootstrap';
import { types as RechargeType } from '../config/Recharge';
import * as UserActions from '../actions/UserActions';
import * as RechargeActions from '../actions/RechargeActions';
import * as RechargeConfigActions from '../actions/RechargeConfigActions';
import Notify from '../common/Notification';
import * as Shell from '../common/Shell';
import * as Util from '../common/Util';
import { share as ShareConfig } from '../config/Common';
import DialogRecharge from '../components/dialog/DialogRecharge';
import DialogAlert from '../components/dialog/DialogAlert';
import DialogCommon from '../components/DialogCommon';
import DialogRechargeContent from '../components/DialogRechargeContent';
import Container from '../components/Container';
import Copyright from '../components/Copyright';

class RechargeApp extends React.Component {

  constructor () {
    super();   
    this.chkProtocl = true;
    this.rechargeType = null;
    this.rechargeData = null;
    this.randcode = null;

    this.state = {
       dialogStyle : "recharge-dialog",
       rechargeModalVisiable : false,
       rechargeModalTitle : "",
       rechargeModalContent : ""
    };

    this.handleRechargeCallBack.bind(this);
  }

  componentDidMount(){
    this.props.rechargeAction.fetchRecharge();
    window.Receiver.addSubscriber(this.handleRechargeCallBack.bind(this));
  }

  componentDidUpdate(){
    let { rechargeConfig } = this.props;
    if (rechargeConfig) {
      let { recharge_result_status = 0, message = "" } = rechargeConfig;

      rechargeConfig.recharge_result_status = 0;

      if (recharge_result_status === -1) {
          this.handleRechargeFailure();
      }else if(recharge_result_status === 1){
          let { price, jf } = rechargeConfig.result;
          let successMessage = `支付成功！你已成功支付${price}元，获得${jf}积分。`;
          this.setState({
            dialogStyle : "",
            rechargeModalContent : <DialogAlert message={ successMessage }/>,
            rechargeModalVisiable : true,
            rechargeModalTitle : `系统提示`,
            rechargeModalButton : [{
               text : "确定",
               style : "default",
               callback : function(){
                  this.props.history.pushState(null, "/User");
               }.bind(this)
            }]
          });
      }
    }
  }

  componentWillUnmount(){
    window.Receiver.removeSubscriber(this.handleRechargeCallBack);
  }

  //支付类型选择
  onRechargeTypeClick(typeItem){
    this.rechargeType = typeItem;
  }

  //支付协议勾选
  handleProtocolChange(value){
    this.chkProtocl = value;
  }

  handleRechargeFailure(){
    this.setState({
      dialogStyle : "",
      rechargeModalContent : <DialogAlert message="您尚未支付成功，是否重新支付？"/>,
      rechargeModalVisiable : true,
      rechargeModalTitle : `系统提示`,
      rechargeModalButton : [{
         text : "重新支付",
         style : "primary",
         callback : function(){
            this.payHandle();
            this.handleDialogHide();
         }.bind(this)
      },{
        text : "取消",
        style : "default"
      }]
    });
  }

  //支付回调处理
  handleRechargeCallBack(param){
    //支付成功
    if(parseInt(param.status) == 1){
       //调用接口，核查支付状态
       this.props.rechargeConfigAction.checkRechargeStatus(this.randcode);
    }else{
       this.handleRechargeFailure();
    }
  }

  //支付订单获取
  getRecharOrder (event){
   
    let rechargeType = this.rechargeType;
    let rechargeData = this.rechargeData;
    if (rechargeType === null) {
      rechargeType = RechargeType[0];
    }

    this.randcode = Util.makeRandomCode(32);

    let orderData = {
      priceid : rechargeData.id,
      paymethod : rechargeType.type,
      randcode : this.randcode
    };

    //请求支付订单
    this.props.rechargeConfigAction.fetchRechargeConfig(orderData);

    //暂时用这种轮询的方式
    let timer = setInterval(function(){ 
      if(this.rechargeData && this.props.rechargeConfig && this.props.rechargeConfig.id){
        clearInterval(timer);
        this.payHandle();
      }
    }.bind(this), 200);

    event.preventDefault();
  }

  //支付流程调用
  payHandle(){
    let rechargeType = this.rechargeType;
    let rechargeData = this.rechargeData;

    if (rechargeType == null) {
      rechargeType = RechargeType[0];
    }

    let rechargeConfig = this.props.rechargeConfig;
    let payParameter;

    //支付宝
    if (rechargeType.id === 1) { 
      payParameter = {
        "partner" : rechargeConfig.parnter,
        "seller" : rechargeConfig.seller,
        "private_key" : rechargeConfig.privatekey,
        "product_name" : rechargeConfig.productname,
        "product_descr" : rechargeConfig.productbody,
        "product_price" : rechargeData.money,
        "out_trade_no" : rechargeConfig.id,
        "notify_url" : rechargeConfig.notifyurl
      }; 
    }else if(rechargeType.id === 2){
      payParameter = {
        "app_id" : rechargeConfig.app_id,
        "mch_id" : rechargeConfig.mch_id,
        "api_key" : rechargeConfig.api_key,
        "product_name" : rechargeConfig.productname,
        "product_descr" : rechargeConfig.productbody,
        "product_price" : rechargeData.money,
        "out_trade_no" : rechargeConfig.id,
        "notify_url" : rechargeConfig.notifyurl
      }; 
    }
    
    Shell.callShellMethod(
      rechargeType.method, 
      null, 
      null, 
      payParameter
    ); 
  }

  //支付进入
  handleRechargeGoClick(event){
    this.setState({
      dialogStyle : "",
      rechargeModalContent : <DialogRecharge handleProtocolChange = { this.handleProtocolChange.bind(this) }/>,
      rechargeModalVisiable : true,
      rechargeModalTitle : `系统提示`,
      rechargeModalButton : [{
         text : "继续",
         style : "primary",
         callback : function(e){
            if(this.chkProtocl === true){
              this.handleDialogHide();
              this.getRecharOrder(e);
            }else{
              Notify.makeNotify("请勾选充值协议");
            }
         }.bind(this)
      },{
        text:"取消",
        style : "default"
      }]
    });

    event.preventDefault();
  }

  //分享处理
  handleShareClick(event){

    //调用分享组件
    Shell.callShellMethod( "sharePlugin",  null, null , ShareConfig );
    event.preventDefault();
  }

  handleRechargeClick(data, event){
    this.rechargeType = null;
    this.rechargeData = data;
    this.setState({
      dialogStyle : "recharge-dialog",
      rechargeModalContent : <DialogRechargeContent data={data} items = {RechargeType} onRechargeTypeClick={ this.onRechargeTypeClick.bind(this) }/>,
      rechargeModalVisiable : true,
      rechargeModalTitle : `请选择支付方式`,
      rechargeModalButton : [{
         text : "去支付",
         style : "danger",
         callback : function(e){
            this.handleRechargeGoClick(e);
         }.bind(this)
      }]
    });

    event.preventDefault();
  }

  handleDialogHide(){
    this.setState({
       rechargeModalVisiable : false
    });
  }

  render() {

    let { user, recharge } = this.props;

    let copyRight = <Copyright/>;
    
    return (
        <Container 
            isGoBack={true} 
            isHeader={true} 
            isFooter={false} 
            copyRight={copyRight}
            headerTitle={"充值"}>
            
            <Well bsSize={"small"} className="well-container border-top-none">
              {
                user.isauth == "1" ? 
                <div className="text-primary">
                  <p className="margin-bottom-none">
                    您是尊贵的华西证券用户&nbsp;<i className="iconfont icon-vip text-danger"></i>
                  </p>
                  <label className="margin-bottom-none">
                    <small className="text-muted">充值积分享受半价优惠</small>
                  </label>
                </div>
                :
                <div className="text-primary">
                  <p className="margin-bottom-none">
                    手机开户，立获200积分
                  </p>
                  <label className="margin-bottom-none">
                    <small className="text-muted">充值积分享受半价优惠</small>
                  </label>
                </div>
              }
               <div className="recharge-remain">
                  <span className="text-danger">
                    账户余额：{user.leftcash||0}积分
                  </span>
               </div>
            </Well>

            <div className="recharge-container">
              
              <h5 className="text-primary recharge-title">
                充值获积分
              </h5>

              <Row>
                   { recharge && recharge.length && recharge.map((recharge, i) =>  
                      <Col xs={4} key={i}>
                        <div className="recharge-item" onClick={ this.handleRechargeClick.bind(this, recharge) }>
                          <h6 className="text-danger"> 
                            { user.isauth == "1" ? recharge.hx_jifen : recharge.nhx_jifen} 积分
                          </h6>
                          <p className="text-primary"> 
                            售价￥{recharge.money}元
                          </p>
                        </div>
                      </Col>
                   )}
              </Row>

              <h5 className="text-primary recharge-title">
                免费获积分
              </h5>

              <Row>
                  <Col xs={6}>
                      <div className="recharge-item" onClick={ this.handleShareClick.bind(this) }>
                        <h6 className="text-danger"> 
                          免费获取50积分
                        </h6>
                        <p className="text-primary"> 
                          帮助一位好友注册
                        </p>
                      </div>
                  </Col>
              </Row>
            </div>

            <DialogCommon 
              className={ this.state.dialogStyle }
              title={ this.state.rechargeModalTitle } 
              content={ this.state.rechargeModalContent } 
              buttons = { this.state.rechargeModalButton }
              visiable={ this.state.rechargeModalVisiable } 
              onHide = { this.handleDialogHide.bind(this) }/>
        </Container>
    );
  }
}

export default connect(state => ({
    recharge : state.recharge,
    user : state.user,
    rechargeConfig : state.rechargeconfig
}), dispatch => ({
    rechargeAction: bindActionCreators(RechargeActions, dispatch),
    userAction: bindActionCreators(UserActions, dispatch),
    rechargeConfigAction: bindActionCreators(RechargeConfigActions, dispatch)
}))(RechargeApp);
